<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    :title="isEdit ? '编辑客户' : '添加客户'"
    width="1100px"
    @close="handleClose"
  >
    <div class="main-content-container">
      <!-- 左侧选项卡 -->
      <div class="left-sidebar">
        <div class="tab-container">
          <div 
            v-for="tab in currentTabsList" 
            :key="tab.name"
            class="tab-item" 
            :class="{ active: activeTab === tab.name }"
            @click="handleTabClick(tab)"
          >
            <span class="tab-text">{{ tab.label }}</span>
          </div>
        </div>
      </div>

      <!-- 中间分割线 -->
      <div class="divider"></div>

      <!-- 右侧内容区域 -->
      <div class="right-content">
        <!-- 基本信息 -->
        <div v-if="activeTab === 'basic'" class="form-content">
          <el-form
            ref="basicInfoRef"
            :model="basicInfo"
            :rules="basicRules"
            class="step-form"
          >
            <el-descriptions :column="1" border class="custom-descriptions">
              <el-descriptions-item label="*统一社会信用代码">
                <el-form-item prop="socialCreditCode" style="margin-top: 15px;">
                  <el-input
                    v-model="basicInfo.socialCreditCode"
                    placeholder="请输入"
                    :disabled="isEdit"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-descriptions-item>

              <el-descriptions-item label="*公司名称">
                <el-form-item prop="companyName" style="margin-top: 15px;">
                  <el-input v-model="basicInfo.companyName" placeholder="请输入" style="width: 100%;" />
                </el-form-item>
              </el-descriptions-item>

              <el-descriptions-item label="*注册资本(万元)">
                <el-form-item prop="registeredCapital" style="margin-top: 15px;">
                  <el-input-number
                    v-model="basicInfo.registeredCapital"
                    :min="0"
                    :precision="2"
                    placeholder="请输入"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-descriptions-item>

              <el-descriptions-item label="*注册地址">
                <el-form-item prop="registeredAddress" style="margin-top: 15px;">
                  <el-cascader
                    v-model="basicInfo.registeredAddress"
                    :options="regionData"
                    :props="cascaderProps"
                    placeholder="请选择省/市/区"
                    style="width: 100%;"
                    clearable
                    filterable
                  />
                </el-form-item>
                <el-form-item prop="registeredAddressDetail" style="margin-top: 10px;">
                  <el-input
                    v-model="basicInfo.registeredAddressDetail"
                    placeholder="请输入详细地址"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-descriptions-item>

              <el-descriptions-item label="*主营业务">
                <el-form-item prop="mainBusiness" style="margin-top: 15px;">
                  <el-input
                    v-model="basicInfo.mainBusiness"
                    type="textarea"
                    placeholder="请输入描述，少于128个字，非必填"
                    :rows="2"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-descriptions-item>

              <el-descriptions-item label="*默认交货地址">
                <el-form-item prop="defaultDeliveryAddress" style="margin-top: 15px;">
                  <el-cascader
                    v-model="basicInfo.defaultDeliveryAddress"
                    :options="regionData"
                    :props="cascaderProps"
                    placeholder="请选择省/市/区"
                    style="width: 100%;"
                    clearable
                    filterable
                  />
                </el-form-item>
                <el-form-item prop="deliveryDetailAddress" style="margin-top: 10px;">
                  <el-input
                    v-model="basicInfo.deliveryDetailAddress"
                    placeholder="请输入详细地址"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-descriptions-item>

              <el-descriptions-item label="*联系人">
                <el-form-item prop="contactPerson" style="margin-top: 15px;">
                  <el-input v-model="basicInfo.contactPerson" placeholder="请输入" style="width: 100%;" />
                </el-form-item>
              </el-descriptions-item>

              <el-descriptions-item label="*联系方式">
                <el-form-item prop="contactInformation" style="margin-top: 15px;">
                  <el-input v-model="basicInfo.contactInformation" placeholder="请输入" style="width: 100%;" />
                </el-form-item>
              </el-descriptions-item>
            </el-descriptions>
          </el-form>
        </div>

        <!-- 财务信息 -->
        <div v-if="activeTab === 'financial'" class="form-content">
          <el-form
            ref="financialInfoRef"
            :model="financialInfo"
            :rules="financialRules"
            class="step-form"
          >
            <el-descriptions :column="1" border class="custom-descriptions">
              <el-descriptions-item label="*纳税人类型">
                <el-form-item prop="taxpayerType" style="margin-top: 15px;">
                  <el-select
                    v-model="financialInfo.taxpayerType"
                    placeholder="请选择"
                    style="width: 100%;"
                  >
                    <el-option label="一般纳税人" value="一般纳税人" />
                    <el-option label="小型纳税人" value="小型纳税人" />
                  </el-select>
                </el-form-item>
              </el-descriptions-item>

              <el-descriptions-item label="*发票类型">
                <el-form-item prop="invoiceType" style="margin-top: 15px;">
                  <el-select
                    v-model="financialInfo.invoiceType"
                    placeholder="请选择"
                    style="width: 100%;"
                  >
                    <el-option label="增值税专用发票" value="增值税专用发票" />
                    <el-option label="普通发票" value="普通发票" />
                    <el-option label="其他" value="其他" />
                  </el-select>
                </el-form-item>
              </el-descriptions-item>

              <el-descriptions-item label="*开户银行">
                <el-form-item prop="invoicingBank" style="margin-top: 15px;">
                  <el-input v-model="financialInfo.invoicingBank" placeholder="请输入" style="width: 100%;" />
                </el-form-item>
              </el-descriptions-item>

              <el-descriptions-item label="*开户账号">
                <el-form-item prop="invoicingBankNumber" style="margin-top: 15px;">
                  <el-input v-model="financialInfo.invoicingBankNumber" placeholder="请输入" style="width: 100%;" />
                </el-form-item>
              </el-descriptions-item>

              <el-descriptions-item label="*开票地址">
                <el-form-item prop="invoiceAddress" style="margin-top: 15px;">
                  <el-cascader
                    v-model="financialInfo.invoiceAddress"
                    :options="regionData"
                    :props="cascaderProps"
                    placeholder="请选择省/市/区"
                    style="width: 100%;"
                    clearable
                    filterable
                  />
                </el-form-item>
                <el-form-item prop="invoiceDetailAddress" style="margin-top: 10px;">
                  <el-input
                    v-model="financialInfo.invoiceDetailAddress"
                    placeholder="请输入详细地址"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-descriptions-item>
            </el-descriptions>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <template v-if="activeTab === 'basic'">
          <el-button type="primary" @click="goToFinancialTab">下一步</el-button>
        </template>
        <template v-else>
          <el-button @click="goToBasicTab">上一步</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </template>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: () => ({})
  },
  regionData: {
    type: Array,
    default: () => []
  },
  tabsList: {
    type: Array,
    default: () => [
      { name: 'basic', label: '基本信息' },
      { name: 'financial', label: '财务信息' }
    ]
  }
})

// 定义emits
const emit = defineEmits(['close', 'confirm', 'update:visible'])

// 当前激活的标签
const activeTab = ref('basic')

// 表单引用
const basicInfoRef = ref(null)
const financialInfoRef = ref(null)

// 级联选择器配置
const cascaderProps = {
  expandTrigger: 'hover',
  checkStrictly: false,
  labelSeparator: '/'
}

// 根据模式决定显示哪些标签（编辑/添加模式只显示基本信息和财务信息）
const currentTabsList = computed(() => {
  // 如果是添加/编辑模式，只显示基本信息和财务信息
  // 查看详情模式时使用传入的tabsList
  if (props.isEdit || !props.visible) {
    return props.tabsList.filter(tab => 
      tab.name === 'basic' || tab.name === 'financial'
    )
  }
  return props.tabsList
})

// 基本信息表单数据
const basicInfo = reactive({
  socialCreditCode: '',
  companyName: '',
  registeredCapital: null,
  registeredAddress: [],
  registeredAddressDetail: '',
  mainBusiness: '',
  defaultDeliveryAddress: [],
  deliveryDetailAddress: '',
  contactPerson: '',
  contactInformation: ''
})

// 财务信息表单数据
const financialInfo = reactive({
  taxpayerType: '',
  invoiceType: '',
  invoicingBank: '',
  invoicingBankNumber: '',
  invoiceAddress: [],
  invoiceAddressDetail: '',
  invoiceAddress: ''
})

// 基本信息表单校验规则
const basicRules = {
  socialCreditCode: [
    { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
    { pattern: /^[A-Z0-9]{18}$/, message: '统一社会信用代码必须是18位大写字母与数字构成', trigger: 'blur' }
  ],
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
  registeredCapital: [
    { required: true, message: '请输入注册资本', trigger: 'blur' }
  ],
  registeredAddress: [
    { required: true, message: '请选择省/市/区', trigger: 'change' },
    { type: 'array', min: 3, message: '请选择完整的省/市/区', trigger: 'change' }
  ],
  registeredAddressDetail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  defaultDeliveryAddress: [
    { required: true, message: '请选择省/市/区', trigger: 'change' },
    { type: 'array', min: 3, message: '请选择完整的省/市/区', trigger: 'change' }
  ],
  deliveryDetailAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactInformation: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 财务信息表单校验规则
const financialRules = {
  taxpayerType: [
    { required: true, message: '请选择纳税人类型', trigger: 'change' }
  ],
  invoiceType: [
    { required: true, message: '请选择发票类型', trigger: 'change' }
  ],
  invoicingBank: [
    { required: true, message: '请输入开户银行', trigger: 'blur' }
  ],
  invoicingBankNumber: [
    { required: true, message: '请输入开户账号', trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: '开户账号必须是16-19位数字', trigger: 'blur' }
  ],
  invoiceAddress: [
    { required: true, message: '请选择省/市/区', trigger: 'change' },
    { type: 'array', min: 3, message: '请选择完整的省/市/区', trigger: 'change' }
  ],
  invoiceDetailAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
}

// 处理标签点击
const handleTabClick = async (tab) => {
  // 从基本信息切换到财务信息时，需要验证基本信息表单
  if (activeTab.value === 'basic' && tab.name === 'financial') {
    try {
      await basicInfoRef.value.validate()
      activeTab.value = tab.name
    } catch (error) {
      ElMessage.error('请完善基本信息')
    }
  } else {
    // 其他切换直接进行
    activeTab.value = tab.name
  }
}

// 前往财务信息标签
const goToFinancialTab = async () => {
  try {
    await basicInfoRef.value.validate()
    activeTab.value = 'financial'
  } catch (error) {
    ElMessage.error('请完善基本信息')
  }
}

// 前往基本信息标签
const goToBasicTab = () => {
  activeTab.value = 'basic'
}

// 处理确认
const handleConfirm = async () => {
  try {
    // 先验证财务信息表单
    await financialInfoRef.value.validate()
    
    // 合并表单数据
    const formData = {
      ...basicInfo,
      ...financialInfo,
      // 合并地址信息
      registeredAddress: `${basicInfo.registeredAddress?.join('/') || ''}/${basicInfo.registeredAddressDetail || ''}`,
      defaultDeliveryAddress: `${basicInfo.defaultDeliveryAddress?.join('/') || ''}/${basicInfo.deliveryDetailAddress || ''}`,
      invoiceAddress: `${financialInfo.invoiceAddress?.join('/') || ''}/${financialInfo.invoiceDetailAddress || ''}`
    }
    
    // 提交数据
    emit('confirm', formData)
    
    // 重置表单
    resetForm()
    emit('update:visible', false)
  } catch (error) {
    ElMessage.error('请完善财务信息')
  }
}

// 处理关闭
const handleClose = () => {
  resetForm()
  emit('update:visible', false)
  emit('close')
}

// 重置表单
const resetForm = () => {
  activeTab.value = 'basic'
  
  if (basicInfoRef.value) {
    basicInfoRef.value.resetFields()
  }
  if (financialInfoRef.value) {
    financialInfoRef.value.resetFields()
  }
  
  // 重置基本信息
  Object.assign(basicInfo, {
    socialCreditCode: '',
    companyName: '',
    registeredCapital: null,
    registeredAddress: [],
    registeredAddressDetail: '',
    mainBusiness: '',
    defaultDeliveryAddress: [],
    deliveryDetailAddress: '',
    contactPerson: '',
    contactInformation: ''
  })
  
  // 重置财务信息
  Object.assign(financialInfo, {
    taxpayerType: '',
    invoiceType: '',
    invoicingBank: '',
    invoicingBankNumber: '',
    invoiceAddress: [],
    invoiceDetailAddress: ''
  })
}

// 监听props变化，当是编辑模式且有editData时填充数据
const updateFormData = () => {
  if (props.isEdit && props.editData) {
    // 填充基本信息
    Object.assign(basicInfo, {
      socialCreditCode: props.editData.socialCreditCode || '',
      companyName: props.editData.companyName || '',
      registeredCapital: props.editData.registeredCapital || null,
      contactPerson: props.editData.contactPerson || '',
      contactInformation: props.editData.contactInformation || '',
      mainBusiness: props.editData.mainBusiness || ''
    })
    
    // 填充财务信息
    Object.assign(financialInfo, {
      taxpayerType: props.editData.taxpayerType || '',
      invoiceType: props.editData.invoiceType || '',
      invoicingBank: props.editData.invoicingBank || '',
      invoicingBankNumber: props.editData.invoicingBankNumber || ''
    })
    
    // 如果有地址信息，尝试解析为级联格式和详细地址
    if (props.editData.registeredAddress) {
      const addressParts = props.editData.registeredAddress.split('/')
      if (addressParts.length >= 3) {
        basicInfo.registeredAddress = addressParts.slice(0, 3)
        basicInfo.registeredAddressDetail = addressParts.slice(3).join('/')
      }
    }
    
    if (props.editData.defaultDeliveryAddress) {
      const addressParts = props.editData.defaultDeliveryAddress.split('/')
      if (addressParts.length >= 3) {
        basicInfo.defaultDeliveryAddress = addressParts.slice(0, 3)
        basicInfo.deliveryDetailAddress = addressParts.slice(3).join('/')
      }
    }
    
    if (props.editData.invoicingAddress) {
      const addressParts = props.editData.invoicingAddress.split('/')
      if (addressParts.length >= 3) {
        financialInfo.invoiceAddress = addressParts.slice(0, 3)
        financialInfo.invoiceDetailAddress = addressParts.slice(3).join('/')
      }
    }
  }
}

// 监听isEdit和editData变化
import { watch } from 'vue'
watch(() => [props.isEdit, props.editData], updateFormData, { deep: true })
</script>

<style scoped>
.dialog-footer {
  margin-top: 20px;
}

/* 从createOutBoundStepForm.vue借鉴的样式 */
.custom-descriptions {
  width: 100%;
}

.custom-descriptions .el-descriptions__item {
  display: flex;
  border-bottom: 1px solid #EBEEF5;
}

.custom-descriptions .el-descriptions__label {
  width: 140px;
  font-weight: 500;
  color: #606266;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  background-color: #f5f7fa;
}

.custom-descriptions .el-descriptions__content {
  flex: 1;
  color: #303133;
  display: flex;
  align-items: flex-start;
  padding: 18px 10px 18px 10px !important;
  min-height: 60px;
}

.custom-descriptions .el-descriptions__row:last-child .el-descriptions__item {
  border-bottom: none;
}

.el-descriptions__cell--label {
  background-color: #f5f7fa !important;
}

:deep(.custom-descriptions .el-descriptions__cell) {
  padding: 0px 11px !important;
}

/* 主要内容容器样式 */
.main-content-container {
  display: flex;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
  min-height: 500px;
}

/* 左侧选项卡样式 */
.left-sidebar {
  width: 200px;
  background-color: #fff;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.config-title {
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-top: 0;
}

.tab-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.tab-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  border-radius: 0;
  cursor: pointer;
  transition: all 0.3s;
}

.tab-item.active {
  background-color: #2457d7;
  color: #fff;
}

.tab-item .dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 10px;
}

.tab-item:not(.active) .dot {
  background-color: #409eff;
}

.tab-item.active .dot {
  background-color: #ccc;
}

.tab-text {
  font-size: 14px;
}

/* 中间分割线样式 */
.divider {
  width: 1px;
  background-color: #e8e8e8;
  height: 100%;
}

/* 右侧内容区域样式 */
.right-content {
  flex: 1;
  background-color: #fff;
  /* padding: 20px; */
  display: flex;
  flex-direction: column;
  min-height: 500px;
  overflow-y: auto;
  border: 1px solid #d9d9d9;
}

/* 表单内容区域 */
.form-content {
  flex: 1;
  overflow-y: auto;
}

/* 级联选择器样式调整 */
:deep(.el-cascader) {
  width: 100%;
}

/* 调整表单间距 */
.el-form-item {
  margin-bottom: 15px;
}
</style>